package com.good.akkaserver.server;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;



public class CommServer {

	private static Logger logger = LoggerFactory.getLogger(CommServer.class);

	private static CommServer server = null;
	

	private static EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 只监听一个端口
	private static EventLoopGroup workerGroup = new NioEventLoopGroup();

	private CommServer() {
	}

	public static synchronized CommServer getInstance() {
		if (server == null) {
			server = new CommServer();
		}
		return server;
	}
	
	private  ServerBootstrap bootstrap;
	
	private ChannelFuture   channelFuture;

	public int startServer(String serverIp, int serverPort) {
			bootstrap = new ServerBootstrap();
	        bootstrap.group(bossGroup, workerGroup);   
	    	bootstrap.channel(NioServerSocketChannel.class);
	    	bootstrap.option(ChannelOption.SO_RCVBUF, 1024);
	    	bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
	        // 设置相关参数
			bootstrap.option(ChannelOption.TCP_NODELAY, true);
			// 设置相关参数
			bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

	        this.bootstrap.option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT);
	        
			final ChannelHandler serverIdleHandler = new ServerIdleHandler();
			ConnectionEventHandler connectionEventHandler = new RpcConnectionEventHandler();
	        this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
	            protected void initChannel(SocketChannel channel) {
	                ChannelPipeline pipeline = channel.pipeline();
	                pipeline.addLast("decoder", new StringDecoder());
	                pipeline.addLast("encoder", new StringEncoder());
	                pipeline.addLast("handler", new CommServerHandler());
	           
                    pipeline.addLast("idleStateHandler", new IdleStateHandler(0, 0, 9000,
                        TimeUnit.MILLISECONDS));
                    pipeline.addLast("serverIdleHandler", serverIdleHandler);
	                pipeline.addLast("connectionEventHandler", connectionEventHandler);
	            }
	        });
			try {
				channelFuture = bootstrap.bind(new InetSocketAddress(serverPort)).sync();
				if (channelFuture.isSuccess()) {
					logger.info("Start Netty Pos Server success! [\"tcp-nio-" +serverPort+ "\"]");
				} else {
					logger.info("Start Netty Pos Server failure!");
				}
				channelFuture.channel().closeFuture().sync();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return 0;
	}

	// 关闭通信服务
	public boolean stopServer() {
	 if (null != this.channelFuture) {
            this.channelFuture.channel().close();
        }
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
		return true;
	}


}
